(function(doc){
   var tools = doc.getElementsByClassName('J_toolsBar')[0],
        can = doc.getElementById('myCanvas'),
        ctx = can.getContext('2d'),
        cWidth = ctx.canvas.width,
        cHeight = ctx.canvas.height,
        color = 'block',
        lineWidth = 4,
        x,
        y;
      
  var  init = function(){
        bindEvent();
    }
    function bindEvent(){
       can.addEventListener('mousedown', function(e){
           mouseDown(e);
           doc.addEventListener('mousemove',mouseMove,false);
           doc.addEventListener('mouseup',mouseUp,false);
       },false);
       
       tools.addEventListener('click',btnClick,false)
    }
    //鼠标按下
    function mouseDown(e){
              _setXy(e);
            ctx.beginPath();
            ctx.strokeStyle = color;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.lineWidth = lineWidth;
            ctx.moveTo(x, y)
    }
    //鼠标移动 
    function mouseMove(e){
        _setXy(e);
        if(x <= 0){
            x = 0;
        }else if( x >= can.offsetWidth){
            x = can.offsetWidth;
        }
        if(y <= 0){
            y = 0;
        }else if(y >= can.offsetHeight){
            y = can.offsetHeight;
        }
        ctx.lineTo(x, y);
        ctx.stroke();

    }
    //鼠标抬起
    function mouseUp(){
        doc.removeEventListener('mousemove',mouseMove,false);
        doc.removeEventListener('mouseup',mouseUp,false);
    }
    function btnClick(e){
      var   e = e || window.event,
            tar = e.target || e.srcElement,
            className = tar.className;
            console.log(className);
            if(className.indexOf('color') === 0){
                color = tar.getAttribute('data-color')
            }
            if(className.indexOf('line') === 0){
                lineWidth = tar.getAttribute('data-line');
            }
            if(className === 'remove'){
                ctx.clearRect(0, 0, cWidth, cHeight)
            }
    }
    //提取获取坐标公共部分
    function _setXy(e){
        var e = e || window.event;
         x = e.pageX - can.offsetLeft;
         y = e.pageY - can.offsetTop;
    }
   init();
})(document);